package com.self.console.web.interceptor;

import java.lang.reflect.Method;
import java.net.URLEncoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.self.console.config.CommonConfig;
import com.self.console.dto.AdminDto;
import com.self.console.web.controller.common.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sangame.sow.ssh.annotation.ActionMode;
import com.sangame.sow.ssh.annotation.NotLogin;
import com.sangame.sow.ssh.orm.hibernate.support.JsonWrapper;
import com.sangame.sow.utils.IpUtils;

/**
 * 过滤非法访问
 */
public class AccessInterceptor extends HandlerInterceptorAdapter {

	private static final Logger LOG = LoggerFactory.getLogger(AccessInterceptor.class);

	@Resource
	private CommonConfig commonConfig;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String contextPath = request.getContextPath();
		String clientIp = IpUtils.getClientIp(request);
		if(commonConfig.isOpenIpFilter()){
			String filterIp = commonConfig.getWhiteIp();
			String[] ips = StringUtils.split(filterIp, ",");
			for(String ip : ips) {
				int index = ip.indexOf("*");
				if (index != -1) {
					ip = ip.substring(0, index);
				}
				if (!clientIp.equals(ip) || !clientIp.startsWith(ip)) {
					if(LOG.isWarnEnabled()){
						LOG.warn("非法访问，IP：" + clientIp + ", 访问URL：" + request.getRequestURL());
					}
					// TODO 需增加一个非法访问的页面
					response.sendRedirect("http://www.cngold.org");
					return false;
				}
			}
		}
		
		HandlerMethod handlerMethod = (HandlerMethod)handler;
		BaseController action = (BaseController)handlerMethod.getBean();
		
		Method method = handlerMethod.getMethod();
		NotLogin notLogin = method.getAnnotation(NotLogin.class);
		
		AdminDto user = (AdminDto) action.getCurrentSession();
		if (notLogin == null && user == null) { // 需要登录
			ActionMode actionMode = method.getAnnotation(ActionMode.class);
			if (actionMode == null) {
				response.sendRedirect(contextPath + "/back/common/login.htm");
			} else if (ActionMode.JSON.equals(actionMode.value())) {
				response.setContentType(MediaType.APPLICATION_JSON_VALUE);
				ObjectMapper objectMapper = new ObjectMapper();
				objectMapper.writeValue(response.getOutputStream(), new JsonWrapper<Object>(true, false, "登录超时", null));
			} else if (ActionMode.PAGE.equals(actionMode.value())) {
				String url = String.format("%s/back/common/jump.htm?message=%s&redirectUrl=%s", 
						contextPath,URLEncoder.encode("登录超时", "UTF-8"),
						URLEncoder.encode(contextPath + "/back/frame/main.htm", "UTF-8"));
				
				response.sendRedirect(url);
			}
			return false;
		}
		return true;
	}
	
}
